package com.zhixiao.user.config

import cn.dev33.satoken.exception.NotLoginException
import cn.dev33.satoken.exception.NotRoleException
import cn.dev33.satoken.util.SaResult
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice

private const val NOT_PERMISSION_MSG = "没有权限"
private const val NOT_LOGIN_MSG = "未登录"

/**
 * 全局异常处理器
 */
@RestControllerAdvice
class GlobalExceptionHandler {

    /**
     * 处理 NotRoleException (角色鉴权失败) 异常
     * 响应 403 状态码
     */
    @ExceptionHandler(NotRoleException::class)
    fun notRoleExceptionHandler(e: NotRoleException?): ResponseEntity<SaResult> {
        val result = SaResult(403, NOT_PERMISSION_MSG, null)
        result.remove("data")
        return ResponseEntity(result, HttpStatus.FORBIDDEN)
    }

    /**
     * 处理 NotLoginException (未登录) 异常
     * 响应 401 状态码
     */
    @ExceptionHandler(NotLoginException::class)
    fun notLoginExceptionHandler(e: NotLoginException?): ResponseEntity<SaResult> {
        val result = SaResult(401, NOT_LOGIN_MSG, null)
        result.remove("data")
        return ResponseEntity(result, HttpStatus.UNAUTHORIZED)
    }

    /**
     * 处理 IllegalArgumentException (参数错误) 异常
     * 响应 400 状态码
     */
     @ExceptionHandler(IllegalArgumentException::class)
    fun illegalArgumentExceptionHandler(e: IllegalArgumentException): ResponseEntity<SaResult> {
        val result = SaResult(400, e.message, null)
        result.remove("data")
        return ResponseEntity(result, HttpStatus.BAD_REQUEST)
    }

    /**
     * 处理其他未知异常
     * 响应 500 状态码
     */
    @ExceptionHandler(Exception::class)
    fun exceptionHandler(e: Exception): ResponseEntity<SaResult> {
        e.printStackTrace()
        val result = SaResult(500, e.message, null)
        result.remove("data")
        result.put("details", e.stackTrace)
        return ResponseEntity(result, HttpStatus.INTERNAL_SERVER_ERROR)
    }

}